from collections import OrderedDict
from datetime import datetime
from time import time
import json

from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from .serializer import *
from util.auth import OWNTokenAuthentication
from util.page import MyPageNumberPagination
from util.exception import ValidationError
from util.xlstool import XlsTool
from .models import *


class ProductsView(GenericViewSet):
    authentication_classes = [OWNTokenAuthentication]

    @action(detail=False, methods=["GET", ], url_path="product_list")
    def product_list(self, requests, *args, **kwargs):
        product_name = requests.GET.get("product_name")
        product_number = requests.GET.get("product_number")
        data = {
            "product_name": product_name if product_name else None,
            "product_number": product_number if product_number else None,
        }
        serializers = ProductCheckSerializer(data=data)
        if serializers.is_valid():
            products = ProductModel.objects
            product_name = serializers.validated_data.get("product_name")
            product_number = serializers.validated_data.get("product_number")
            if product_name:
                products = products.filter(product_name__icontains=product_name)
            if product_number:
                products = products.filter(product_number__icontains=product_number)
            products = products.filter(is_delete=False).all()
            page = MyPageNumberPagination()
            page_usrs = page.paginate_queryset(queryset=products, request=requests, view=self)
            gateway_re = ProductListSerializer(instance=page_usrs, many=True)
            return Response(self.__get_paginated_response(page, requests, gateway_re.data))
        else:
            raise ValidationError(20001)

    def __get_paginated_response(self, page, request, datas):
        a = OrderedDict([
            ('current', int(page.get_page_number(request, page))),
            ('total', int(page.page.paginator.count)),
            ('pageSize', int(page.get_page_size(request))),
            ('data', datas),
            ("code", 200)

        ])
        return a

    @action(detail=False, methods=["GET", ], url_path="productformlist")
    def productformlist(self, requests, *args, **kwargs):
        products = ProductModel.objects.filter(is_delete=False).all()
        result = {}
        for pro in products:
            result.update({pro.product_number: pro.product_number})
        return Response({"code": 200, "result": result})

    @action(detail=False, methods=["GET", ], url_path="productadd_list")
    def prodcutadd_list(self, requests, *args, **kwargs):
        products = ProductModel.objects.filter(is_delete=False).all()
        result = []
        for pro in products:
            result.append({
                "label": pro.product_number,
                "value": pro.product_number,
            })
        return Response({"code": 200, "result": result})

    @action(detail=False, methods=["POST", ], url_path="product_create")
    def productcreate(self, requests, *args, **kwargs):
        data = requests.query_params
        product_number =  data.get("product_number")
        product_name = data.get("product_name")
        data = {
            "product_number": product_number if product_number else None,
            "product_name": product_name if product_name else None
        }
        serializer = productCreateSerializer(data=data)
        if serializer.is_valid():
            serializer.create(serializer.validated_data)
            return Response({"code": 200, "msg": "添加成功"})
        raise ValidationError(20001)

    @action(detail=False, methods=["POST", ], url_path="product_update")
    def productupdate(self, requests, *args, **kwargs):
        id = requests.query_params.get("id")
        product_name = requests.query_params.get("product_name")
        product_number = requests.query_params.get("product_number")
        is_delete = requests.query_params.get("is_delete")
        data = {
            "id": id if id else None,
            "product_name": product_name if product_name else None,
            "product_number": product_number if product_number else None,
            "is_delete": is_delete if is_delete else None,
        }
        serializer = productUpdateSerializer(data=data)
        if serializer.is_valid():
            key = serializer.create(serializer.validated_data)
            return Response({"code": 200, "msg": "修改成功"})
        raise ValidationError(20001)
